<?php

# Setup classes
include_once(dirname(__FILE__).'/ajaxResource.php');

# Define variables
$invalidInput = false;

# Resource rating
if($siteBuilder->post['type'] == 'resource') {
	
	$key = 'resourceID';
	$table = 'resources_ratings';	
	
} elseif($siteBuilder->post['type'] == 'book') {
	
	$key = 'ISBN';
	$table = 'books_ratings';	
	
} else {

	$invalidInput = true;	
	
}

# We did something wrong
if($invalidInput !== true) {

	# Get ratings
	$ratings = $siteBuilder->db->getRow("SELECT COUNT(*) as totalVotes, SUM(rating) as sumVotes, (
		SELECT userID FROM {$table}
		WHERE {$key} = '{$siteBuilder->post['ID']}' AND userID = '{$siteBuilder->user['userID']}'
	) AS userHasVoted FROM {$table} 
	WHERE {$key} = '{$siteBuilder->post['ID']}'");

}

# Has the user voted?
if(empty($ratings) || ($ratings['userHasVoted'] == $siteBuilder->user['userID'])) {
		
	$return['userHasVoted'] = true;	
		
} else {
	
	$return['userHasVoted'] = false;	
	
	# Insert rating
	$siteBuilder->db->query("INSERT INTO {$table} SET {$key} = '{$siteBuilder->post['ID']}', userID = '{$siteBuilder->user['userID']}', rating = '{$siteBuilder->post['rating']}'");
		
	# Alter rating
	$ratings['sumVotes'] += $siteBuilder->post['rating'];
	$ratings['totalVotes']++;
		
	# Average
	$average = round($ratings['sumVotes'] / $ratings['totalVotes'], 1);
	
}

# Return average, new width
if(!$return['userHasVoted']) {
	$return['width'] = ($average * 2) * 10 + ((ceil($average) - 1) * 10);
	$return['percentage'] = $average;
	$return['voteCast'] = $ratings['totalVotes'].' vote'.(($ratings['totalVotes'] != 1) ? 's' : '').' cast';
}

# Return response
echo(json_encode($return));

# Release memory
unset($siteBuilder);

?>